package com.sf.dlb.service;

import com.sf.dlb.bean.UserReportBean;
import com.sf.dlb.constant.CacheConstant;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.UserReportInfo;
import com.sf.dlb.jpa.repository.UserReportRepository;
import com.sf.dlb.mongo.model.NewInfo;
import com.sf.dlb.mongo.model.NewList;
import com.sf.dlb.mongo.repository.NewInfoRepository;
import com.sf.dlb.mongo.repository.NewListRepository;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.PageVO;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class UserReportServiceBase extends BaseService {
    private static Logger logger = LoggerFactory.getLogger(UserReportServiceBase.class);

    @Autowired
    private NewInfoRepository newInfoRepository;
    @Autowired
    private NewListRepository newListRepository;
    @Autowired
    private UserReportRepository userReportRepository;

    /**
     * 添加举报
     * @return
     */
    @Transactional
    public ResultVO addReport(String userId,String reportType,String reportId,String reportDesc){
        logger.info("addReport userId={},reportType={},shieldId={}",userId,reportType,reportId);
        //并发操作
        String key= CacheConstant.USER_CACHE+CacheConstant.USER_REPORT_PREFIX+userId+":"+reportId;
        boolean concurrentFlag=isConcurrent(key);
        if(concurrentFlag){
            return ResultVOUtil.error(ResponseConstant.ERROR,"不能重复举报");
        }
        UserReportInfo userReportInfo=new UserReportInfo();
        userReportInfo.setUserId(userId);
        userReportInfo.setReportType(reportType);
        userReportInfo.setReportId(reportId);
        userReportInfo.setReportDesc(reportDesc);
        userReportInfo.setProcessState("1");
        userReportInfo.setCreateDate(new Date());
        userReportInfo.setUpdateDate(new Date());
        userReportRepository.save(userReportInfo);
        return ResultVOUtil.success();
    }
    /**
     * 举报列表
     * @return
     */
    public ResultVO reportList(UserReportBean userReportBean){
        logger.info("reportList userReportBean={}", GsonUtils.getInstance().toJson(userReportBean));
        UserReportInfo userReportInfo=new UserReportInfo();
        int page=userReportBean.getPage();
        int size=userReportBean.getSize();
        if(StringUtils.isNoneBlank(userReportBean.getUserId())){
            userReportInfo.setUserId(userReportBean.getUserId());
        }
        if(StringUtils.isNoneBlank(userReportBean.getReportType())){
            userReportInfo.setReportType(userReportBean.getReportType());
        }
        if(StringUtils.isNoneBlank(userReportBean.getReportId())){
            userReportInfo.setReportId(userReportBean.getReportId());
        }
        if(StringUtils.isNoneBlank(userReportBean.getProcessState())){
            userReportInfo.setProcessState(userReportBean.getProcessState());
        }
        userReportInfo.setDelFlag("0");
        Example example=Example.of(userReportInfo);
        Sort sort=new Sort(Sort.Direction.DESC,"createDate");
        Pageable pageable=new PageRequest(page,size,sort);
        Page<UserReportInfo> pageAll=userReportRepository.findAll(example,pageable);
        List<UserReportInfo> userReportInfoList=pageAll.getContent();
        List<UserReportVO> userReportVOS=new ArrayList<>();
        for (UserReportInfo userReportInfo1:userReportInfoList) {
            UserReportVO userReportVO=new UserReportVO();
            BeanUtils.copyProperties(userReportInfo1,userReportVO);
            userReportVO.setReportTypeValue(StateToValueUtils.switchReportType(userReportInfo1.getReportType()));
            userReportVO.setProcessStateValue(StringUtils.equals(userReportInfo1.getProcessState(),"0")?"已处理":"未处理");
            userReportVO.setProcessWayValue(StateToValueUtils.switchProcessWay(userReportInfo1.getProcessWay()));
            userReportVO.setCreateDate(userReportInfo1.getCreateDate().getTime());
            userReportVOS.add(userReportVO);
        }
        PageVO pageVO=new PageVO();
        pageVO.setDataList(userReportVOS);
        pageVO.setPageSize(size);
        pageVO.setCurrentPages(page+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(pageAll.isFirst());
        pageVO.setLastPage(pageAll.isLast());
        pageVO.setTotalElements(pageAll.getTotalElements());
        pageVO.setTotalPages(pageAll.getTotalPages());
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 举报处理
     * @return
     */
    @Transactional
    public ResultVO reportHandler(String id,String processWay,String processDesc){
        logger.info("reportHandler id={},processWay={},processDesc={}",id,processWay,processDesc);
        //更新处理状态
        UserReportInfo userReportInfo=userReportRepository.getOne(Long.valueOf(id));
        if(StringUtils.equals(userReportInfo.getProcessState(),"0")){
            logger.info("reportHandler userReportInfo.getProcessState()==0");
            return ResultVOUtil.error(ResponseConstant.ERROR,"此举报已处理");
        }
        userReportInfo.setProcessState("0");
        userReportInfo.setProcessWay(processWay);
        userReportInfo.setProcessDesc(processDesc);
        userReportInfo.setUpdateDate(new Date());
        userReportRepository.save(userReportInfo);
        //执行处理逻辑
        if(StringUtils.equals(processWay,"1")){
            logger.info("reportHandler userReportInfo.getReportType()={}",userReportInfo.getReportType());
            switch (userReportInfo.getReportType()){
                case "1":
                    //新闻
                    reportNewsHandler(userReportInfo.getReportId());
                    break;
                case "2":
                    break;
                case "3":
                    break;
            }
        }else{
            logger.info("reportHandler processWay==0");
        }
        return ResultVOUtil.success();
    }
    /**
     * 举报-新闻处理
     */
    @Transactional
    public void reportNewsHandler(String newsId){
        logger.info(" reportNewsHandler start newsId={}",newsId);
        NewList newList=newListRepository.findByIdAndDelFlag(newsId,"0");
        if(null!=newList){
            newListRepository.delete(newList);
            NewInfo newInfo=newInfoRepository.findByIdAndDelFlag(newList.getNewInfoId(),"0");
            if(null!=newInfo){
                newInfoRepository.delete(newInfo);
            }
        }
    }
}
